package com.definesys.smecrailtransit.module.Navigation;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.android.annotations.Nullable;
import com.definesys.smecrailtransit.MainActivity;
import com.definesys.smecrailtransit.R;
import com.definesys.smecrailtransit.SmecApplication;
import com.definesys.smecrailtransit.SmecManager.SmecDialog.SmecDialog;
import com.definesys.smecrailtransit.SmecManager.SmecRealm.RealmManager;
import com.definesys.smecrailtransit.SmecManager.SmecSession.SmecSession;
import com.definesys.smecrailtransit.api.SmecRailConstant;
import com.definesys.smecrailtransit.base.SmecBaseActivity;
import com.definesys.smecrailtransit.databinding.ActivityNavigationBinding;
import com.definesys.smecrailtransit.module.Login.LoginActivity;
import com.definesys.smecrailtransit.module.Navigation.beans.Cuebeans;
import com.definesys.smecrailtransit.receiver.JPushReceiver;
import com.definesys.smecrailtransit.receiver.receiverBean.JPushExtras;
import com.definesys.smecrailtransit.service.Notification.NotificationService;
import com.definesys.smecrailtransit.utils.ToastyUtils;
import com.definesys.smecrailtransit.widget.TopBarLayout;
import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.widget.NormalDialog;
import com.github.mzule.activityrouter.annotation.Router;
import com.github.mzule.activityrouter.router.Routers;
import com.hwangjr.rxbus.annotation.Subscribe;
import com.hwangjr.rxbus.annotation.Tag;
import com.hwangjr.rxbus.thread.EventThread;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

import static com.definesys.smecrailtransit.module.Login.LoginActivity.LOGIN_SEWITCH;
import static com.definesys.smecrailtransit.module.Navigation.NavigationAdapter.NavigationAdapter.NAVIGATION;
import static com.definesys.smecrailtransit.receiver.JPushReceiver.ACTIVITY_OPENDED;

/**
 * Created by cjy on 2017/8/13.
 */
@Router("NavigationActivity")
public class NavigationActivity extends SmecBaseActivity<NavigationPresenter> {

    public static final String MAINACTIVITY_FINISH="MAINACTIVITY_FINISH";
    private ActivityNavigationBinding activityNavigationBinding;
    private NormalDialog normalDialog;
    private int currentPage=0;
    private boolean isExit=false;
    private Handler mHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            isExit=true;
        }
    };
    private SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activityNavigationBinding = DataBindingUtil.setContentView(this, R.layout.activity_navigation);
        _initView();
    }

    /**
     * 初始化信息
     */
    private void _initView(){
        _setJpushAlias();
        _startUploadSerice();
        SmecRailConstant.initConstant();
        activityNavigationBinding.getRoot().postDelayed(new Runnable() {
            @Override
            public void run() {
                mPresenter.getAllStations(new HashMap<>());
                mPresenter.getAttention(new HashMap<>());
            }
        },200);

        activityNavigationBinding.naviLoginOut.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(normalDialog == null){
                    normalDialog = SmecDialog.getInstance(NavigationActivity.this,"退出登录");
                    normalDialog.setOnBtnClickL(
                            new OnBtnClickL() {
                                @Override
                                public void onBtnClick() {
                                    normalDialog.dismiss();
                                }
                            },
                            new OnBtnClickL() {
                                @Override
                                public void onBtnClick() {
                                    normalDialog.dismiss();
                                    mHandler.postDelayed(new Runnable() {
                                        @Override
                                        public void run() {
                                            mRxBus.post(LoginActivity.LOGIN_SEWITCH,new Object());
                                        }
                                    },300);
                                }
                            });
                }
                normalDialog.show();
            }
        });

//        TextView nvaiView=activityNavigationBinding.topBarLayout.gettvTextRightSecond();
//        ViewGroup.LayoutParams layoutParams=nvaiView.getLayoutParams();
//        layoutParams.height=60;
//        layoutParams.width=60;
//        nvaiView.setBackground(getResources().getDrawable(R.drawable.navi_switch));

        activityNavigationBinding.topBarLayout.setTopBarListener(new TopBarLayout.TopBarListener() {
            @Override
            public void setOnLeftClickListener() {

            }

            @Override
            public void setOnRight1ClickListener() {

            }

            @Override
            public void setOnRight2ClickListener() {
//                Routers.open(NavigationActivity.this,"smec://RenYanActivity");
            }
        });

        activityNavigationBinding.smecCue.setVisibility( isShowCue() ? View.VISIBLE :View.INVISIBLE);
    }

    private boolean isShowCue(){
        Cuebeans cuebeans=(Cuebeans) RealmManager.getInstance().findFirst(Cuebeans.class);
        if(cuebeans == null || cuebeans.getDate() == null){
            return true;
        }
        if(cuebeans.getDate().equals(simpleDateFormat.format(new Date()))){
            return false;
        }else {
            return true;
        }
    }

    /**
     * 点击事件
     * @param view
     */
    public void navigaClick(View view){
        switch (view.getId()){
            case R.id.real_msg:
                currentPage=0;
                break;
            case R.id.site_details:
                currentPage=1;
                break;
            case R.id.real_status:
                currentPage=2;
                break;
            case R.id.fault_st:
                currentPage=3;
                break;
            case R.id.operator_status:
                currentPage=4;
                break;
            case R.id.line_report:
                currentPage=5;
                Cuebeans cuebeans=new Cuebeans();
                cuebeans.setId(1);
                cuebeans.setDate(simpleDateFormat.format(new Date()));
                RealmManager.getInstance().insertOrUpdate(cuebeans);
                break;
            case R.id.smec_record:
                currentPage=6;
                break;
        }
        Intent intent=new Intent(NavigationActivity.this, MainActivity.class);

        String[] param = new String[3];
        param[0] = currentPage+ "";
        param[1] = "";
        param[2] = "";

        intent.putExtra(NAVIGATION, param);
        startActivity(intent);
    }

    @Override
    protected void onResume() {
        super.onResume();
        activityNavigationBinding.smecCue.setVisibility( isShowCue() ? View.VISIBLE :View.INVISIBLE);
    }

    /**
     * 设置推送信息
     */
    private void _setJpushAlias(){
        JPushInterface.setAlias(this, SmecSession.getSmecUser().getUserId(), new TagAliasCallback() {
            @Override
            public void gotResult(int i, String s, Set<String> set) {
                if(i==0){
                    Log.e("我是设置别名成功",i+" "+SmecSession.getSmecUser().getUserId());
                }
            }
        });
    }

    private void _startUploadSerice(){
        if(!SmecApplication.isServiceWork(this,"com.definesys.smecrailtransit.service.Notification.NotificationService")){
            Intent service = new Intent(this, NotificationService.class);
            startService(service);
        }
    }

    @Subscribe(
            thread = EventThread.MAIN_THREAD,
            tags = {
                    @Tag(ACTIVITY_OPENDED)
            }
    )
    public void openedActivity(JPushExtras jPushExtras){
        String funName = jPushExtras.getFunName();

        if(SmecRailConstant.isForeground(NavigationActivity.this,"com.definesys.smecrailtransit.module.Navigation.NavigationActivity")){
            if(funName !=null && !funName.equals("")){
                if(funName.equals(JPushReceiver.JPUSH_TYPE_REAL)){
                    currentPage=0;
                }
                if(funName.equals(JPushReceiver.JPUSH_TYPE_REPORT)){
                    currentPage=1;
                }
                if(funName.equals(JPushReceiver.JPUSH_TYPE_STATISTICS)){
                    currentPage=3;
                }
                if(funName.equals(JPushReceiver.JPUSH_TYPE_RUNTIME)){
                    currentPage=4;
                }
                if(funName.equals(JPushReceiver.JPUSH_TYPT_LINE_REPORT)){
                    currentPage =5;
                }

                Intent intent=new Intent(NavigationActivity.this, MainActivity.class);

                String[] param = new String[3];
                param[0] = currentPage+ "";
                param[1] = jPushExtras.getFrom();
                param[2] = jPushExtras.getTo();

                intent.putExtra(NAVIGATION, param);
                startActivity(intent);
            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (!isExit) {
                isExit = true;
                ToastyUtils.showNormalToast(this,getString(R.string.press_again_quit_android));
                mHandler.sendEmptyMessageDelayed(0, 2000);
            } else {
                appManager.finishAllActivity();
                System.exit(0);
            }
        }
        return false;
    }


    @Override
    public NavigationPresenter getPresenter() {
        return new NavigationPresenter(this);
    }

    @Subscribe(

            thread = EventThread.MAIN_THREAD,
            tags = {
                    @Tag(LOGIN_SEWITCH)
            }
    )

    public void loginSwitch(Object o){
        finish();
    }

    @Subscribe(

            thread = EventThread.MAIN_THREAD,
            tags = {
                    @Tag(MAINACTIVITY_FINISH)
            }
    )

    public void mainfinist(Object o){
        activityNavigationBinding.smecCue.setVisibility( isShowCue() ? View.VISIBLE :View.INVISIBLE);
        activityNavigationBinding.invalidateAll();
    }

}
